package com.blog.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.dto.UserInfoDTO;
import com.blog.entity.Notification;
import com.blog.entity.User;
import com.blog.service.NotificationService;
import com.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/notifications")
public class NotificationController {

    @Autowired
    private NotificationService notificationService;

    @Autowired
    private UserService userService;

    /**
     * 获取用户通知列表
     */
    @GetMapping
    public ResponseEntity<Page<Notification>> getUserNotifications(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        if (!StpUtil.isLogin()) {
            return ResponseEntity.status(401).body(null);
        }

        Long userId = StpUtil.getLoginIdAsLong();
        Page<Notification> page = notificationService.getUserNotifications(userId, pageNum, pageSize);

        // 加载通知发起者信息
        List<Long> initiatorIds = page.getRecords().stream()
                .map(Notification::getInitiatorId)
                .distinct()
                .collect(Collectors.toList());

        Map<Long, User> userMap = new HashMap<>();
        if (!initiatorIds.isEmpty()) {
            List<User> users = userService.listByIds(initiatorIds);
            users.forEach(user -> userMap.put(user.getId(), user));
        }

        // 处理通知中的用户信息等
        page.getRecords().forEach(notification -> {
            // 可以在这里处理通知的额外信息，如发起者昵称等
            User queryUser = userService.getById(notification.getInitiatorId());
            if(queryUser!=null){
                UserInfoDTO userInfoDTO = new UserInfoDTO();
                userInfoDTO.setNickname(queryUser.getNickname());
                userInfoDTO.setAvatar(queryUser.getAvatar());
                notification.setFromUser(userInfoDTO);
            }else{
                notification.setFromUser(null);
            }

        });

        return ResponseEntity.ok(page);
    }

    /**
     * 获取未读通知数量
     */
    @GetMapping("/unread/count")
    public ResponseEntity<Integer> getUnreadCount() {
        if (!StpUtil.isLogin()) {
            return ResponseEntity.status(401).body(null);
        }

        Long userId = StpUtil.getLoginIdAsLong();
        Integer count = notificationService.getUnreadCount(userId);

        return ResponseEntity.ok(count);
    }

    /**
     * 标记通知为已读
     */
    @PutMapping("/{notificationId}/read")
    public ResponseEntity<Map<String, Object>> markAsRead(@PathVariable Long notificationId) {
        if (!StpUtil.isLogin()) {
            return ResponseEntity.status(401).body(null);
        }

        Long userId = StpUtil.getLoginIdAsLong();
        boolean success = notificationService.markAsRead(notificationId, userId);

        if (success) {
            return ResponseEntity.ok(Map.of("message", "标记已读成功"));
        } else {
            return ResponseEntity.badRequest().body(Map.of("message", "标记已读失败"));
        }
    }

    /**
     * 标记所有通知为已读
     */
    @PutMapping("/read/all")
    public ResponseEntity<Map<String, Object>> markAllAsRead() {
        if (!StpUtil.isLogin()) {
            return ResponseEntity.status(401).body(null);
        }

        Long userId = StpUtil.getLoginIdAsLong();
        boolean success = notificationService.markAllAsRead(userId);

        if (success) {
            return ResponseEntity.ok(Map.of("message", "全部标记已读成功"));
        } else {
            return ResponseEntity.ok(Map.of("message", "没有未读通知"));
        }
    }

    /**
     * 删除通知
     */
    @DeleteMapping("/{notificationId}")
    public ResponseEntity<Map<String, Object>> deleteNotification(@PathVariable Long notificationId) {
        if (!StpUtil.isLogin()) {
            return ResponseEntity.status(401).body(null);
        }

        Long userId = StpUtil.getLoginIdAsLong();

        // 检查通知是否属于当前用户
        Notification notification = notificationService.getById(notificationId);
        if (notification == null || !notification.getUserId().equals(userId)) {
            return ResponseEntity.badRequest().body(Map.of("message", "无权操作该通知"));
        }

        boolean success = notificationService.removeById(notificationId);

        if (success) {
            return ResponseEntity.ok(Map.of("message", "删除成功"));
        } else {
            return ResponseEntity.badRequest().body(Map.of("message", "删除失败"));
        }
    }
}
